<?php

namespace App\Http\Controllers\API\Find;

use Carbon\Carbon;
use App\Models\API\Activity;
use Illuminate\Http\Request;
use App\Http\Controllers\API\APIController;

class FindController extends APIController
{
    public function index()
    {
        $now = Carbon::now();

    	$activities = Activity::where('start_time', '>=', $now)
        ->orderBy('id', 'desc')
        ->join('users', 'activities.user_id', '=', 'users.id')
        ->select('activities.*', 'users.user_name', 'users.user_img')
        ->withCount('activityApply', 'activityJoin')
        ->paginate(10);
        
    	return response()->json($activities, 200);
    }

    public function girls()
    {
        $now = Carbon::now();

        $activities = Activity::where('start_time', '>=', $now)
        ->orderBy('id', 'desc')
        ->join('users', function($join) {
            $join->on('activities.user_id', '=', 'users.id')
                 ->where('sex', '女');
        })
        ->select('activities.*', 'users.user_name', 'users.user_img')
        ->withCount('activityApply', 'activityJoin')
        ->paginate(10);

        return response()->json($activities, 200);
    }

    public function boys()
    {
        $now = Carbon::now();

        $activities = Activity::where('start_time', '>=', $now)
        ->orderBy('id', 'desc')
        ->join('users', function($join) {
            $join->on('activities.user_id', '=', 'users.id')
                 ->where('sex', '男');
        })
        ->select('activities.*', 'users.user_name', 'users.user_img')
        ->withCount('activityApply', 'activityJoin')
        ->paginate(10);

        return response()->json($activities, 200);
    }

    public function search(Request $request)
    {
    	$theme = ['派对', '旅行', '假期', '生日', '学习', '运动', '美食', '公益', '其他'];

    	$title = $request->get('title');

        $now = Carbon::now();

    	$results;

    	if (in_array($title, $theme)) {
    		$results = Activity::where([
                ['theme', $title],
                ['start_time', '>=', $now]
            ])
            ->orderBy('id', 'desc')
            ->join('users', 'activities.user_id', '=', 'users.id')
            ->select('activities.*', 'users.user_name', 'users.user_img')
            ->withCount('activityApply', 'activityJoin')
            ->paginate(10);
    	}else{
    		$results = Activity::where([
                ['title', 'like', '%'.$title.'%'],
                ['start_time', '>=', $now]
            ])
            ->orderBy('id', 'desc')
            ->join('users', 'activities.user_id', '=', 'users.id')
            ->select('activities.*', 'users.user_name', 'users.user_img')
            ->withCount('activityApply', 'activityJoin')
            ->paginate(10);
    	}

    	return response()->json($results, 200);
    }
}
